package com.bytech.admin.biz.service.music.Impl;

import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bytech.common.biz.entity.base.BaseResult;
import com.bytech.common.biz.entity.music.Music;
import com.bytech.admin.biz.mapper.music.MusicMapper;
import com.bytech.admin.biz.service.music.MusicService;
import com.bytech.common.biz.entity.music.MusicDto;
import com.bytech.common.biz.entity.music.MusicQuery;
import com.bytech.common.biz.enums.CommonStatusEnum;
import com.bytech.common.biz.service.base.BasicServiceImpl;
import com.bytech.common.utils.StringUtils;

import org.springframework.stereotype.Service;

/**
 * @Author Zhao
 * @Create 2021-12-23
 */
@Service
public class MusicServiceImpl extends BasicServiceImpl<MusicMapper, Music> implements MusicService {

    @Override
    public BaseResult<?> add(Music music) {
        BaseResult<?> checkResult = checkMusic(music);
        if (checkResult.isFailure()) {
            return checkResult;
        }
        music.setStatus(CommonStatusEnum.NORMAL.getValue());
        music.setCreateTime(new Date());
        save(music);
        return BaseResult.success("保存成功！").build();
    }

    private BaseResult<?> checkMusic(Music music) {
        if (StringUtils.isBlank(music.getName())) {
            return BaseResult.error("音乐名称不能为空").build();
        }
        if (StringUtils.isBlank(music.getMusicUrl())) {
            return BaseResult.error("音乐文件路径不能为空 ").build();
        }
        if (StringUtils.isBlank(music.getArtist())) {
            music.setArtist(null);
        }
        return BaseResult.success().build();
    }

    @Override
    public Page<MusicDto> pageArticleByQuery(MusicQuery<Music> query) {
        LambdaQueryWrapper<Music> queryWrapper = buildMusicQuery(query);
        page(query, queryWrapper);
        return query.translateRecordsTo(MusicDto.class);
    }

    private LambdaQueryWrapper<Music> buildMusicQuery(MusicQuery<Music> query) {
        LambdaQueryWrapper<Music> queryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isBlank(query.getArtist())) {
            queryWrapper.like(Music::getArtist, query.getArtist());
        }
        if (!StringUtils.isBlank(query.getName())) {
            queryWrapper.like(Music::getName, query.getName());
        }
        if (!StringUtils.isBlank(query.getStatus())) {
            queryWrapper.eq(Music::getStatus, query.getStatus());
        }
        return queryWrapper;
    }
}
